import { stringify } from 'querystring';
import type { Reducer, Effect } from 'umi';
import { history } from 'umi';

import { fakeAccountLogin } from '@/services/auth/login';
// import { queryCurrent } from '@/services/auth/user';
// import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { message } from 'antd';

export type StateType = {
  status?: 'ok' | 'error';
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
  access_token?:string;
  refresh_token?:string;
  expireTime?:number;
};

export type LoginModelType = {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
};

const Model: LoginModelType = {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(fakeAccountLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // //查询权限
      // const userResp = yield call(queryCurrent);
      // console.log('-----查询用户信息---试试---')
      // console.log(userResp)

      console.log('-----------------登录成功-------------')
      // Login successfully
      console.log(response)
      const urlParams = new URL(window.location.href);
      const params = getPageQuery();
      message.success('🎉 🎉 🎉  登录成功！');
      let { redirect } = params as { redirect: string };
      if (redirect) {
        const redirectUrlParams = new URL(redirect);
        if (redirectUrlParams.origin === urlParams.origin) {
          redirect = redirect.substr(urlParams.origin.length);
          if (window.routerBase !== '/') {
            redirect = redirect.replace(window.routerBase, '/');
          }
          if (redirect.match(/^\/.*#/)) {
            redirect = redirect.substr(redirect.indexOf('#') + 1);
          }
        } else {
          window.location.href = '/';
          return;
        }
        history.replace(redirect || '/');
      }
    },

    logout() {
      const { redirect } = getPageQuery();
      // Note: There may be security issues, please note
      if (window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
      //清空token
      localStorage.setItem("access_token","");
      localStorage.setItem("refresh_token","");
      localStorage.setItem("expireTime","");
    },
  }, 

  reducers: {
    changeLoginStatus(state, { payload }) {
      console.log('-----------------登录陈宫----')
      console.log(payload)
      const data = payload
      localStorage.setItem("access_token",data.access_token);
      localStorage.setItem("refresh_token",data.refresh_token);
      const current = new Date()
      const expireTime = current.setTime(current.getTime() + 1000 * data.expires_in)
      localStorage.setItem("expireTime",expireTime+"");

      // setAuthority(payload.currentAuthority);
      return {
        ...state,
        status: payload.status,
        type: payload.type,
        access_token:data.access_token,
        refresh_token:data.refresh_token,
        expireTime:expireTime,
      };
    },
  },
};

export default Model;
